package com.shao.loadBalance;

import com.shao.SrpcBootstrap;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/5/6 16:34
 */
public abstract class AbstractLoadBalancer implements LoadBalancer {

    private final ConcurrentHashMap<String, Selector> SELECT_CACHE = new ConcurrentHashMap<>(8);

    @Override
    public InetSocketAddress selectServiceAddress(String serviceName) {
        Selector selector = SELECT_CACHE.get(serviceName);
        if (selector == null) {
            List<InetSocketAddress> addresses = SrpcBootstrap.getInstance().getConfiguration().getRegistryConfig().getRegistry().lookup(serviceName);
            // 轮询负载均衡器缓存服务列表
            selector = getSelector(addresses);
            SELECT_CACHE.put(serviceName, selector);
        }
        return selector.getNext();
    }

    @Override
    public void reLoadBalancer(String serviceName, List<InetSocketAddress> addresses) {
        SELECT_CACHE.put(serviceName, getSelector(addresses));
    }

    /**
     * 由子类进行拓展
     * @param addresses 服务列表
     * @return 返回负载均衡选择器
     */
    protected abstract Selector getSelector(List<InetSocketAddress> addresses);
}
